package com.fingard.dsp.bank.directbank.gycb01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class GYCB01Transaction extends GYCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                int startPatches = 1;
                boolean queryContinue = true;
                while (queryContinue) {
                    //Thread.sleep(1000);
                    GYCB01Header bankHeader = new GYCB01Header();
                    bankHeader.batchID = getQryTransID();
                    bankHeader.transName = "B2eQueryActDetail4UTF8";
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    int countRd = 0;
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, bankHeader);
                    xmlWriter.writeStartElement("RequestRecord");
                    xmlWriter.writeElementString("AcctNo", p_req7516.actNum);
                    xmlWriter.writeElementString("BeginDate", Format.Date10Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("EndDate", Format.Date10Format.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeElementString("PageNo", String.valueOf(startPatches));
                    xmlWriter.writeElementString("QueryNo", "20");
                    xmlWriter.writeElementString("BeginMoney", "");
                    xmlWriter.writeElementString("EndMoney", "");
                    xmlWriter.writeEndDocument();
//                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), p_req7516.reqHeader.transType, p_req7516.reqHeader.commandCode);

                    XmlTextReader tmpBkReader;
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String respondCode = tmpBkReader.getSimpleText("respondCode");
                            String respondInfo = tmpBkReader.getSimpleText("respondInfo");
                            if (respondCode != null && respondCode.equals("RET2000")) {
                                // #start "提取各返回节点内容"
                                while (tmpBkReader.read("/transaction/RespondBody/RespondRecord")) {
                                    {
                                        countRd++;
                                        //tmpRespCode = "0";
                                        tmpRespInfo = "success";
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        XElement tmpRetNode = tmpBkReader.readedXElement;
                                        String dealDate = tmpRetNode.getSingleText("HostTxnDate");
                                        tmpRetDetail.actNum = p_req7516.actNum;
                                        tmpRetDetail.tranDate = dealDate.substring(0, 4) + "-" + dealDate.substring(4, 6) + "-" + dealDate.substring(6, 8);
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;//格式yyyy-MM-dd
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate + " 00:00:00";//格式"yyyy-MM-dd HH:mm:ss"
                                        tmpRetDetail.usage = tmpRetNode.getSingleTextNotNull("Note").trim();
                                        tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                        tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("AcctNo2").trim();
                                        tmpRetDetail.recAccName = tmpRetNode.getSingleTextNotNull("Acct2Name").trim();
                                        tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("Acct2BankName").trim();
                                        tmpRetDetail.accBal = tmpRetNode.getSingleText("AcctBalance");
                                        String cdflag = tmpRetNode.getSingleText("CrDtIndicator");//0 借 1贷
                                        String amout = tmpRetNode.getSingleText("Amount");
                                        if ("0".equals(cdflag)) {
                                            if (amout.contains("-")) {
                                                tmpRetDetail.cdFlag = "2";
                                            } else {
                                                tmpRetDetail.cdFlag = "1";
                                            }
                                        }else if ("1".equals(cdflag)) {
                                            if (amout.contains("-")) {
                                                tmpRetDetail.cdFlag = "1";
                                            } else {
                                                tmpRetDetail.cdFlag = "2";
                                            }
                                        } else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "借贷标志(" + cdflag + ")无法识别，请与银行核对";
                                            break;
                                        }

                                        tmpRetDetail.tranAmt = amout.replace("-", "");
                                        tmpRetDetail.originator = tmpRetNode.getSingleText("HostJournalNo");
                                        tmpRetDetail.payCode = tmpRetNode.getSingleText("PTJnlNo");

                                        nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());

                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                                if (countRd >= 20) {
                                    startPatches++;
                                } else {
                                    queryContinue = false;
                                }
                            } else {
                                //  "查询失败"
                                tmpRespCode = "-1";
                                tmpRespInfo = respondInfo;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;//设置开始时间和结束时间都为当天
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
